package com.neuedu.yyzx.service.impl;

import com.neuedu.yyzx.controller.UploadController;
import com.neuedu.yyzx.entity.Upload;
import com.neuedu.yyzx.mapper.UploadMapper;
import com.neuedu.yyzx.service.IUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author keyu
 * @since 2024-05-06
 */
@Service
public class UploadServiceImpl extends ServiceImpl<UploadMapper, Upload> implements IUploadService {
    static final String UPLOAD_DIR = "D:\\foodupload\\";
    @Override
    public Map upload(HttpServletRequest request) {
        Map map = new HashMap();
        map.put("success", false);
        /**
         * 获取上传文件
         */
        //判断是否支持  Multipart
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");

            try {
                List<FileItem> items = upload.parseRequest((RequestContext) request);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        String filePath = UPLOAD_DIR + fileName;
                        File storeFile = new File(filePath);
                        //保存文件
                        item.write(storeFile);
                        map.put("success", true);
                        map.put("fileName", fileName);
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }
//        Map map = new HashMap();
//        Map.put("success", false);

    /**
     * 上传操作
     */
    //判断是否支持  Multipart
//        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//
//        if (isMultipart) {
//            DiskFileItemFactory factory = new DiskFileItemFactory();
//
//            // Configure a repository (to ensure a secure temp location is used)
//            //设置 Tomcat 接收到 文件 存放到那个临时目录
//            ServletContext servletContext = request.getServletContext();
//            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
//            factory.setRepository(repository);
//            // Create a new file upload handler
//            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
//
//            //解析 Request的流
//
//            try {
//                List<FileItem> fileItems = servletFileUpload.parseRequest((RequestContext) request);
//                for (FileItem fileItem : fileItems) {
//
//
//                    String name = fileItem.getName();// package.png
//                    String fieldName = fileItem.getFieldName();  //abc
//                    String uuid = UUID.randomUUID().toString().replace("-", "");
//                    String ext = name.substring(name.lastIndexOf("."));
//
//                    String newFileName = uuid + ext;
//                    File dist = new File(UPLOAD_DIR + newFileName);
//
//
//                    fileItem.write(dist);//讲文件 从临时目录 转出到   D;\\upload
//
//                    Upload upload = new Upload();
//                    upload.setExt(ext);
//                    upload.setOriginName(fieldName);
//                    upload.setPath(newFileName);
//                    upload.setUpTime(new Date());
//                    upload.setUpUser("admin");
//                    UploadController.saveOrUpdate(upload);
//
//
//                    map.put("success", true);
//                    map.put("id", upload.getUploadId());
//
//                }
//            } catch (FileUploadException e) {
//                throw new RuntimeException(e);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        }
//        return map;
//    }

    @Override
    public Map download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map map = new HashMap();
        String uploadId = request.getParameter("uploadId");
        Upload upload = UploadMapper.selectOne(" where upload_id = ?", uploadId);
        String path = UPLOAD_DIR + upload.getPath();
        File file = new File(path);
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(upload.getOriginName(), "UTF-8"));
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            fis.close();
            os.close();
        }
        return map;
    }

    @Override
    public Object selectOne(String where, Object[] params) {
        return null;
    }

}
